package edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.service;

import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.dao.SysUserDAO;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.entity.SysUserEntity;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.utils.MD5Utils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SysUserService {

    private final SysUserDAO userDao;

    public SysUserService(SysUserDAO userDao) {
        this.userDao = userDao;
    }

    /**
     * 根据用户名和密码获取用户
     * 设计原则体现：
     * 1. 单一职责原则(SRP) - 方法只负责用户认证
     * 2. 关注点分离 - 数据访问逻辑与业务逻辑分离
     */
    public SysUserEntity getByUserAndPwd(String name, String pwd) {

        SysUserEntity entity = new SysUserEntity();
        entity.setName(name);
        entity.setPassword(MD5Utils.md5(pwd));

        Example<SysUserEntity> entityExample = Example.of(entity);

        List<SysUserEntity> list = userDao.findAll(entityExample);

        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 根据ID获取用户
     * 设计原则体现：
     * 1. 高内聚 - 方法功能单一，专注于获取用户
     * 2. 依赖倒置原则 - 通过DAO接口获取数据
     */
    public SysUserEntity getById(Long id) {
        Optional<SysUserEntity> optional = userDao.findById(id);

        return optional.orElse(null);
    }
}
